package za.org.jcicada.comms.impl;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import za.org.jcicada.comms.IConnection;
import za.org.jcicada.comms.messages.CommsMessage;

public abstract class MessagingBase extends MessageListenerBase {

    private static final Log logger = LogFactory.getLog(MessagingBase.class);

    /**
     * Handle to connection object for message communication.
     */
    private IConnection connection;

    /**
     * Constructor sets up message handler to dispatch messages to this class.
     */
    public MessagingBase(IConnection connection) {
        this.connection = connection;
    }
    
    /**
     * Base class provides sendMessage method for sending messages back via a katcomms
     * connection.
     */
    public class ResponderBase {

        /**
         * Try to send the message but log an error if something goes wrong
         * @param message object to be sent
         */
        protected void sendMessage(CommsMessage message) {
            if (logger.isTraceEnabled()) {
                logger.trace(String.format("%s sending %s.", getClass().getName(), message.getClass().getName()));
            }
            try {
                connection.sendMessage(message);
            } catch (IOException ex) {
                logger.error(String.format("%s failed to send message", getClass().getName()), ex);
            }
        }
        
        /**
	     * Default implementation for informDisconnect which does nothing. This is
	     * called to notify that a connection has been closed by the peer. It is not
	     * meant to be called to close the connection. Therefore when implementing
	     * this method in derived classes do not use this event to try to close the
	     * connection.
		 */
        public final void informDisconnect() {
        }
    }

}
